using System;
using System.Windows.Forms;
using System.Collections;
using System.IO;

namespace Logger
{
    ///<summary>
    /// UI code class
    ///</summary>
    public partial class MainForm : Form
    {
        private TaskLogger _tskLogger;
        private bool _isTaskPaused;
        private bool _isStartInProgress;
        private readonly string _historyFile;//Issue 2: Task history
        private readonly ArrayList _historyList;//Issue 2: Task history
        private const int _baloonTipElapseTime = 10 * 1000;//10 seconds in milliseconds

        ///<summary>
        /// Main form constructor
        ///</summary>
        public MainForm()
        {
            _historyFile = Application.StartupPath + "\\task_history.txt";
            _historyList = new ArrayList();
            if(!File.Exists(_historyFile))
            {
                File.Create(_historyFile).Close();// Issue 15: Initial crash after startup
            }
            InitializeComponent();            
        }

        /* Issue 2: Task history */
        private void UpdateHistoryList()
        {
            StreamReader reader = new StreamReader(_historyFile);
            while(!reader.EndOfStream)
            {
                _historyList.Add(reader.ReadLine());
            }
            reader.Close();
        }

        /* Issue 2: Task history */
        private void UpdateHistoryFile(string taskName)
        {
            if(_historyList.Contains(taskName))
                return;
            _historyList.Add(taskName);
            StreamWriter writer = new StreamWriter(_historyFile, true);
            writer.WriteLine(taskName);
            writer.Close();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(_tskLogger.IsTaskAvailable())
            {
                DialogResult result = MessageBox.Show("Task in progress. Save before exit?", 
                    "Logger", MessageBoxButtons.YesNoCancel,
                    MessageBoxIcon.Exclamation);
                switch (result)
                {
                    case DialogResult.Yes:
                        _tskLogger.EndCurrentTask(DateTime.Now);
                        Application.Exit();
                        break;
                    case DialogResult.No:
                        _tskLogger.CancelTask();
                        Application.Exit();
                        break;
                    default:
                        return;
                }
            }
            else
            {
                Application.Exit();
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            /* Issue 13: Hiding application in the task-switcher */
            Hide();
            _tskLogger = new TaskLogger(Application.StartupPath + "\\task_logger.xml");
            _isTaskPaused = false;
            _isStartInProgress = false;
            UpdateMenuItems();
            /* Ballon notification */
            notifyLogger.BalloonTipText = "Double-click to start a new task.\nRight-click for more options";
            notifyLogger.BalloonTipTitle = "Logger";
            notifyLogger.ShowBalloonTip(_baloonTipElapseTime);//10 seconds baloon tip during startup
            UpdateHistoryList();
        }

        private void UpdateMenuItems()
        {
            if(_tskLogger.IsTaskAvailable())
            {
                pauseToolStripMenuItem.Enabled = !_isTaskPaused;
                stopToolStripMenuItem.Enabled = true;
            }
            else
            {
                pauseToolStripMenuItem.Enabled = false;
                stopToolStripMenuItem.Enabled = false;
            }
            resumeToolStripMenuItem.Enabled = _isTaskPaused;
        }

        private void startNewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(_isStartInProgress)
                return;
            if (!_tskLogger.IsTaskAvailable())
            {
                _isStartInProgress = true;
                NewTask newTask = new NewTask(_historyList);
                if (newTask.ShowDialog() != DialogResult.OK)
                {
                    _isStartInProgress = false;
                    return;
                }
                _isStartInProgress = false;
                string taskName = newTask.Description;
                UpdateHistoryFile(taskName);//Issue 2: Task history
                if (!_tskLogger.StartNewTask(taskName, DateTime.Now))
                {
                    MessageBox.Show("Error creating new task", "Logger", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {
                _isStartInProgress = true;
                string stopOption = (_isTaskPaused) ? ("Cancel ") : ("End ");
                if(DialogResult.Yes == MessageBox.Show(stopOption+"current task and start a new one?", "Logger", MessageBoxButtons.YesNo,
                                MessageBoxIcon.Information))
                {
                    stopToolStripMenuItem_Click(sender, e);
                    _isStartInProgress = false;
                    startNewToolStripMenuItem_Click(sender, e);
                }
                _isStartInProgress = false;
            }
            UpdateMenuItems();
            stopToolStripMenuItem.Text = "Stop";
        }

        private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(!_tskLogger.PauseCurrentTask(DateTime.Now))
            {
                MessageBox.Show("Error in pausing task", "Logger", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            stopToolStripMenuItem.Text = "Cancel";
            _isTaskPaused = true;
            UpdateMenuItems();
        }

        private void resumeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(!_tskLogger.ResumeCurrentTask(DateTime.Now))
            {
                MessageBox.Show("Error in resuming task", "Logger", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            stopToolStripMenuItem.Text = "Stop";
            _isTaskPaused = false;
            UpdateMenuItems();
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(_isTaskPaused)
            {
                _tskLogger.CancelTask();
                _isTaskPaused = false;
            }
            else
            {
                if(!_tskLogger.EndCurrentTask(DateTime.Now))
                {
                    MessageBox.Show("Error in stopping task", "Logger", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            Text = "Stop";
            UpdateMenuItems();
        }

        private void todayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(dlgSaveCsv.ShowDialog() == DialogResult.OK)
            {
                if(_tskLogger.ExportToCsv(dlgSaveCsv.FileName, TaskLogger.Report.Today, DateTime.Now, DateTime.Now))
                {
                    MessageBox.Show("Report Generated successfully", "Logger", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);    
                }
                else
                {
                    MessageBox.Show("No record available", "Logger", MessageBoxButtons.OK,
                                MessageBoxIcon.Information); 
                }
                
            }
        }

        private void customToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReportRangePicker rangePicker = new ReportRangePicker();
            if(rangePicker.ShowDialog() == DialogResult.OK)
            {
                if (dlgSaveCsv.ShowDialog() == DialogResult.OK)
                {
                    if(_tskLogger.ExportToCsv(dlgSaveCsv.FileName, TaskLogger.Report.Range, rangePicker.StartTime, rangePicker.EndTime))
                    {
                        MessageBox.Show("Report Generated successfully", "Logger", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);    
                    }
                    else
                    {
                        MessageBox.Show("No record available", "Logger", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                    }
                }
            }
        }
    }
}